<?php 
class shop_models_admin extends CI_Model{
	public function __construct(){
		$this->load->database();
	}
   public function create($shop){
   		if(isset($shop->photo) and is_array($shop->photo)){
   			$shop->logo=$shop->photo[0];
   			unset($shop->photo);
   		}

   		if(isset($shop->photo))
   			unset($shop->photo);
   		
   		$shop->shop_link=self::valide_link($shop->shop_link);
   		//creer produit
	   	$this->db->insert('shop', $shop);
	   	//prendre id auto increment
	   	$shop->id=$this->db->insert_id();
   		return 	$shop->id;
   }

   public function get_list_shop($filter=array(),$sort=array(),$paging=array(),$limit=20){
   	if(is_array($paging)){
   		$limit=$paging['number_affiche'];
   		$current=$paging['page_current']*$limit;
   	}else{
   		$current=0;
   		if(is_numeric($paging)) $current=$paging;
   	}
   	$where='';
   	$orderBy='';
   	$condition=array();
   	foreach ($filter as $nameFilter=>$valueFilter)
   	if(!empty($valueFilter)){
   		$where=' WHERE ';
   		break;
   	}
   	if(!empty($sort))
   	foreach ($sort as $sortName=>$valueSort)
   		$orderBy="ORDER BY $sortName $valueSort";
   
   	if($where){
   		if(isset($filter['category']) and $filter['category'])
   			$condition['category']='category_id='.$filter['category'];
   		if(isset($filter['category_id']) and $filter['category_id'])
   			$condition['category']='category_id='.$filter['category_id'];
   		if(isset($filter['search_cp']) and $filter['search_cp'])
   			$condition['cp']='code_postal='.$filter['search_cp'];
   		if(isset($filter['search_region']) and $filter['search_region']){
   			$extract=explode(',',$filter['search_region']);
   			if(!empty($extract)){
   				foreach ($extract as $key=>$value)$extract[$key]="'$value'";
   				$filter['search_region']=implode(',',$extract);
   			}
   			$condition['region']="departement in (".$filter['search_region'].")";
   		}

   		$filter['']=$this->input->post('search_region'); 

   		if(isset($filter['search']) and $filter['search']){
   			$search[]=" company_name like '%".$filter['search']."%'";
   			$search[]=" tilte like '%".$filter['search']."%'";
   			$search[]=" description like '%".$filter['search']."%'";
   			$condition['search']= "(".implode(' OR ',$search).")";
   			unset($search);
   		}
   		if(isset($filter['date']) and $filter['date']){
   			$condition[]="DATE_FORMAT(DATE( FROM_UNIXTIME(shop.date_validate ) ),'%Y%m' )='{$filter['date']}'";
   		}
   		if(!empty($condition))$where.= implode(' AND ',$condition);
   	}
   $sql="SELECT id
   	FROM shop
   	$where
   	$orderBy
   	LIMIT $current,$limit
   	";
   	$get= $this->db->query($sql);
   	
   	//si il y a aucun resultat ne correponds a la recherche on cherche mots par mots
   	if($get->num_rows()==0 and isset($condition['search'])){
   		$extract=explode(' ',$filter['search']);
   		if(count($extract)>=2){
   			unset($condition['search']);
   			foreach ($extract as $word_search){
   				$search[]=" company_name like '%".$word_search."%'";
   				$search[]=" tilte like '%".$word_search."%'";
   				$search[]=" description like '%".$word_search."%'";
   				$temp_condition[]= "(".implode(' OR ',$search).")";
   				unset($search);
   			}
   			$condition['search']= "(".implode(' OR ',$temp_condition).")";
   		}
   		if(!empty($condition))$where = ' WHERE '.implode(' AND ',$condition);
   		$sql="SELECT id
   		FROM shop
   		$where
   		$orderBy
   		LIMIT $current,$limit
   		";
   		$get= $this->db->query($sql);
   	}
   	
   	$result=array();
   	//custom and add value to object shop
   	foreach ($get->result() as $row){
   		$result[]= self::get_info_shop($row->id);
   	}
   	return $result;
   
   }
   
   public function total_list_shop($filter=array()){

   	$where='';
   	$condition=array();
   	foreach ($filter as $nameFilter=>$valueFilter)
   	if(!empty($valueFilter)){
   		$where=' WHERE ';
   		break;
   	}
   if($where){
   		if(isset($filter['category']) and $filter['category'])
   			$condition[]='category_id='.$filter['category'];
   		if(isset($filter['category_id']) and $filter['category_id'])
   			$condition[]='category_id='.$filter['category_id'];
   		if(isset($filter['search_cp']) and $filter['search_cp'])
   			$condition[]='code_postal='.$filter['search_cp'];
   		if(isset($filter['search_region']) and $filter['search_region']){
   			$extract=explode(',',$filter['search_region']);
   			if(!empty($extract)){
   				foreach ($extract as $key=>$value)$extract[$key]="'$value'";
   				$filter['search_region']=implode(',',$extract);
   			}
   			$condition[]="departement in (".$filter['search_region'].")";
   		}

   		$filter['']=$this->input->post('search_region'); 

   		if(isset($filter['search']) and $filter['search']){
   			$search[]=" company_name like '%".$filter['search']."%'";
   			$search[]=" tilte like '%".$filter['search']."%'";
   			$search[]=" description like '%".$filter['search']."%'";
   			$condition['search']= "(".implode(' OR ',$search).")";
   			unset($search);
   		}
   		if(isset($filter['date']) and $filter['date']){
   			$condition[]="DATE_FORMAT(DATE( FROM_UNIXTIME(shop.date_validate ) ),'%Y%m' )='{$filter['date']}'";
   		}
   		if(!empty($condition))$where.= implode(' AND ',$condition);
   	}
   	$sql="SELECT count(id) as total
   	FROM shop
   	$where
   	LIMIT 1
   	";
   	$get= $this->db->query($sql);
   	$row=$get->result();
   	
   	if($row[0]->total==0 and isset($condition['search'])){
   		$extract=explode(' ',$filter['search']);
   		if(count($extract)>=2){
   			unset($condition['search']);
   			foreach ($extract as $word_search){
   				$search[]=" company_name like '%".$word_search."%'";
   				$search[]=" tilte like '%".$word_search."%'";
   				$search[]=" description like '%".$word_search."%'";
   				$temp_condition[]= "(".implode(' OR ',$search).")";
   				unset($search);
   			}
   			$condition['search']= "(".implode(' OR ',$temp_condition).")";
   		}
   		if(!empty($condition))$where = ' WHERE '.implode(' AND ',$condition);
   		$sql="SELECT count(id) as total
				   	FROM shop
				   	$where
				   	LIMIT 1
				   	";
   		$get= $this->db->query($sql);
   		$row=$get->result();
   	}
   	
   	
   	 return $row[0]->total;
   }
   
   public function get_info_shop($id,$search='',$page=0,$limit=20){
	   	$query = $this->db->get_where('shop', array('id' => $id), 1);
	   	$row=false;
	   	if($query->num_rows()){
	   		$shop= $query->result();
	   		$row=$shop[0];
	   		$row->site='http://'.str_replace(array('http://','https://'),'',$row->site);
	   		//departement name
	   		$query = $this->db->get_where('departement_nom', array('code_departement' => $row->departement), 1);
	   		$rw= $query->result();
	   		$row->departement_name=isset($rw[0])?$rw[0]->nom:'';
	   		//city name
	   		$query = $this->db->get_where('departement_ville', array('Cp' => $row->code_postal), 1);
	   		$rw= $query->result();
	   		$row->ville=isset($rw[0])?$rw[0]->N_Com_min:'';
	   		//category's name
	   		$query = $this->db->get_where('category', array('id' => $row->category_id), 1);
	   		$rw= $query->result();
	   		$row->category_name=isset($rw[0])?$rw[0]->name:'';
	   		$row->category_link=isset($rw[0])?$rw[0]->link:'';
	   		
	   		//number of annonce
	   		$condition= array('user_email' => $row->email);
	   		
	   		$this->db->select('count(*) as total')->from('product')->where($condition);
	   		if(is_array($search))$this->db->where_in('prd_id',$search);
	   		$query = $this->db->get();
	   		$result=$query->result();
	   		$row->num_product=$row->nb_annonces=$result[0]->total;

	   		$this->db->select('*')->from('product')->where($condition)->limit($limit,$page );
	   		if(is_array($search))$this->db->where_in('prd_id',$search);
	   		$query = $this->db->get();
	   		if($query->num_rows())$row->tous_annonces=$query->result();
	   		
	   		//total paid for notice
	   		$query = $this->db->select_sum('prd_paid')->from('product')->where(array('shop_id'=>$row->id))->get();
	   		$rw= $query->result();
	   		$row->total=isset($rw[0])?$rw[0]->prd_paid:'';
	   	}
	   	return $row;
   }
   public function get_month_year_create($limit=''){
   	if($limit) $limit=" LIMIT $limit";
   	$get= $this->db->query("SELECT DISTINCT DATE_FORMAT(DATE( FROM_UNIXTIME( date_validate ) ),'%Y%m' )AS YearMonth,
   			DATE_FORMAT(DATE( FROM_UNIXTIME( date_validate ) ),'%m' )AS month,
   			DATE_FORMAT(DATE( FROM_UNIXTIME( date_validate ) ),'%Y' )AS year
   			from shop  $limit");
   			return $get->result();
   
   }
   public function get_total_shop($active=FALSE){
   	if($active) $active=" WHERE shop_active=1";
   	else $active='';
   	$get= $this->db->query("SELECT count(*) as numShop FROM shop $active");
   	$row=$get->result();
   	 
   	return $row[0]->numShop;
   }
   public function deactive($id){
   	$this->db->update('shop', array('shop_active'=>0), array('id'=> $id));
   }

   public function delete($id){
   	$this->db->delete('shop', array( "id" => $id));
   	$this->db->update('product', array('shop_id'=>0), array("shop_id" => $id));
   }
   public function reactive($id){
   	$this->db->update('shop', array('shop_active'=>1), array('id'=> $id));
   }
   public function edit($shop){
	   	$query = $this->db->get_where('shop', array('id' => $shop->id), 1);
	   	if($query->num_rows()){
	   		$row=$query->result();
	   		if($shop->shop_link!=$row[0]->shop_link)
	   			$shop->shop_link=self::valide_link($shop->shop_link);
	   	}
   		
   		$this->db->update('shop', $shop, "id = {$shop->id}");
   }

   private function valide_link($page_link){
   	$query = $this->db->get_where('shop', array('shop_link' => $page_link), 1);
   	if($query->num_rows()){
   		$random=substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyz"), 0, 4);
   		return $page_link.'-'.$random;
   	}
   	return $page_link;
   }
}